import React, { useEffect } from 'react';
import { DatePicker, Row, Col } from 'antd';
import moment from 'moment';
import { DATE_OPTIONS } from './configs';
import CheckTag from '../CheckTag';
import { useSetState } from 'ahooks';

type ChangeFunction = {
  (type: 'summaryDate', value?: string): void;
  (type: 'timeRange', value: string): void;
};

type Value = {
  summaryDate: string;
  timeRange: string;
};

const DateFrom: React.FC<{
  onChange?: any;
  defaultValue?: Value;
  value?: Value;
  isTag?: Boolean
}> = ({ onChange, defaultValue, value: externalValue, isTag = true }) => {
  const [{ timeRange, summaryDate }, setValue] = useSetState<any>({
    summaryDate: defaultValue?.summaryDate,
    timeRange: defaultValue?.timeRange,
  });

  const handleChange: ChangeFunction = (type: any, val: any) => {
    setValue({ [type]: val });
    onChange(Object.assign({ timeRange, summaryDate }, { [type]: val }));
  };

  useEffect(() => {
    if (externalValue) {
      setValue(externalValue)
    }
  }, [externalValue]);

  return (
    <Row gutter={8} align="middle" justify="space-between">
      <Col>
        <DatePicker
          allowClear={false}
          value={moment(summaryDate)}
          onChange={value => handleChange('summaryDate', value?.format('YYYY-MM-DD'))}
          disabledDate={current => current.isBefore(moment().subtract(1, 'years').startOf('day'))}
        />
      </Col>
      {isTag && <Col>
        <CheckTag
          value={timeRange}
          onChange={value => handleChange('timeRange', value)}
          options={DATE_OPTIONS}
        />
      </Col>}
    </Row>
  );
};

export default DateFrom;
